﻿/*
 * Created by SharpDevelop.
 * User: Guy Fomi
 * Date: 2/6/2011
 * Time: 2:14 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace TomatoSynchronizer.Store
{
	/// <summary>
	/// Description of CouponStore.
	/// </summary>
	public class CouponStore
	{
		private Site _site;
		private HtmlWeb _client;
		
		public CouponStore(Site site,HtmlWeb client)
		{
			_site = site;
			_client = client;
		}
		
		private IDictionary GetCoupon(string CouponId)
		{
			List<IDictionary> entries = new List<IDictionary>();
			
			HtmlDocument doc = _client.Load(_site.Url + "/admin/json.php?action=load_coupons&coupons_id=" + CouponId + "&module=coupons");
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			List<IDictionary> categories = new List<IDictionary>();
			List<IDictionary> products = new List<IDictionary>();
			foreach(string key in json.Keys)
			{
				if(key == "data")
				{
					IDictionary Coupon = (IDictionary)json[key];					
					
					foreach(string cle in Coupon.Keys)
					{
						switch(cle)
						{
							case "categories":								
								object[] recs = (object[])Coupon[cle];
								for(int i = 0;i < recs.Length;i++)
								{
									IDictionary category = (IDictionary)recs[i];
									categories.Add(category);
								}								
								break;
							case "products":								
								object[] produits = (object[])Coupon[cle];
								for(int i = 0;i < produits.Length;i++)
								{
									IDictionary product = (IDictionary)produits[i];
									products.Add(product);
								}								
								break;
						}
					}
					
					Coupon["products"] = products;
					Coupon["categories"] = categories;
					entries.Add(Coupon);
				}
			}
			
			return entries[0];
		}
		
		public List<IDictionary> GetCoupons()
		{
			List<IDictionary> Coupons = new List<IDictionary>();
			
			HtmlDocument doc = _client.Load(_site.Url + "/admin/json.php?action=list_coupons&module=coupons");
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			IDictionary json = serialiser.Deserialize<IDictionary>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "records")
				{
					object[] recs = (object[])json[key];
					for(int i = 0;i < recs.Length;i++)
					{
						IDictionary record = (IDictionary)recs[i];
						IDictionary Coupon = GetCoupon(record["coupons_id"].ToString());
						Coupons.Add(Coupon);
					}
				}
			}
			
			return Coupons;
		}
	}
}
